import crypto from 'node:crypto'

import { Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { RedisService } from 'src/redis/redis.service'
import { UserCreateDTO } from 'src/user/user.dto'
import { UserService } from 'src/user/user.service'

import { AuthLoginDTO, AuthRegisterDTO } from './auth.dto'

const hash = crypto.createHash('sha256')

/**
 * token 1小时过期
 * redis TTL 以秒为单位
 */
const TOKEN_EXPIRATION = 60 * 60

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
    private readonly redisService: RedisService
  ) {}

  public register(payload: AuthRegisterDTO) {
    const data: UserCreateDTO = {
      password: hash.update(payload.password).digest('hex'),
      mobile: payload.mobile,
      name: payload.name
    }

    return this.userService.createUser(data)
  }

  public async signIn(payload: AuthLoginDTO) {
    const token = this.jwtService.sign(payload)

    await this.redisService.cache.set(token, payload, TOKEN_EXPIRATION)

    return token
  }

  public async validateUserAccount(mobile: string) {
    const user = await this.userService.findAccount(mobile)

    return user ?? null
  }

  public async validateUserAccountAndPasswd(mobile: string, password: string) {
    const user = await this.userService.findAccountWithPasswd(mobile, password)

    return user ?? null
  }
}
